package cn.net.autocode.platform.function.service;

import cn.net.autocode.core.utils.TreeUtils;
import cn.net.autocode.dbManager.Dao;
import cn.net.autocode.platform.design.handle.AutoCodeHandle;
import cn.net.autocode.platform.design.vo.AppInfo;
import cn.net.autocode.platform.design.vo.DeveloperInfo;
import cn.net.autocode.platform.design.webclient.AcWebClient;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("platformFuncServ")
public class FuncServ {
    private final Dao dictDao;

    private final AcWebClient acWebClient;

    public FuncServ(@Qualifier("dictDao")Dao dictDao, AcWebClient acWebClient) {
        this.dictDao = dictDao;
        this.acWebClient = acWebClient;
    }

    public JSONArray queryPageTree(){
        return this.queryPageTree(false);
    }

    public JSONArray queryPageTree(boolean onlySelectLeaf){

        JSONArray arrays = new JSONArray();
        JSONArray categorys = dictDao.queryJSONArray("select * from ac_category where type='category' order by code");
        for(int i=0;i<categorys.size();i++){
            JSONObject category = categorys.getJSONObject(i);
            category.put("id","category_"+category.getString("code"));
            category.put("parentId", "0");
            category.put("disabled",onlySelectLeaf);
        }
        arrays.addAll(categorys);
        JSONArray applications = dictDao.queryJSONArray("select * from ac_category where type='application' order by code");
        arrays.addAll(applications);
        int len=applications.size();
        for(int i=0;i<len;i++){
            JSONObject application = applications.getJSONObject(i);
            application.put("id","application_"+application.getString("code"));
            application.put("parentId","category_"+application.getString("parentCode"));
            application.put("disabled",onlySelectLeaf);
        }

        JSONArray pageArrays = dictDao.queryJSONArray("select id,code,label,category_code  from ac_page order by code");
        int len2=pageArrays.size();
        for(int i=0;i<len2;i++){
            JSONObject page = pageArrays.getJSONObject(i);
            page.put("parentId","application_"+page.getString("categoryCode"));
            page.put("type","page");
            page.put("isLeaf",true);
        }
        arrays.addAll(pageArrays);
        return TreeUtils.commonTree(arrays);
    }


    public void getReleaseVersion(String pageId){
        JSONObject json = dictDao.queryJSON("select * from ac_page where id=?",pageId);
        if(json.isEmpty()){
            return;
        }
        JSONObject pageJson = new JSONObject();
        pageJson.put("categoryCode",json.getString("categoryCode"));
        pageJson.put("code",json.getString("code"));

        JSONArray versions = dictDao.queryJSONArray("select release_time,release_user,version from ac_page_versions where page_id=? order by release_time desc",pageId);
        if(versions.isEmpty()){
            pageJson.put("version","-1");
        }else{
            pageJson.put("version",versions.getJSONObject(0).getString("version"));
            pageJson.put("releaseTime",versions.getJSONObject(0).getString("releaseTime"));
            pageJson.put("releaseUser",versions.getJSONObject(0).getString("releaseUser"));
        }

        DeveloperInfo developerInfo = AutoCodeHandle.getDeveloperInfo();
        if(developerInfo==null){
            throw new RuntimeException("没有登陆开发者账号，请先在右上角的【开发者信息】栏中进行登陆！");
        }

        JSONArray array = acWebClient.getReleaseVersion(pageJson);
        int maxVersion = 0;
        for(int i=0;i<array.size();i++){
            JSONObject releasePage = array.getJSONObject(i);
            releasePage.put("pageId",json.getString("id"));
            releasePage.put("updateTime",new Date());
            releasePage.put("updateUser", developerInfo.getUsername());
            maxVersion = releasePage.getIntValue("version");
            dictDao.createJSON(releasePage,"ac_page_versions");
        }
        //保留50个版本
        if(maxVersion>30){
            dictDao.executeUpdate("delete from ac_page_versions where page_id=? and version<?",pageId,maxVersion-30);
        }
        if (maxVersion>0){
            dictDao.executeUpdate("update ac_page set max_version=?,version=? where id=?",maxVersion,maxVersion,pageId);
        }
    }

    public void syncFunc(){
        JSONObject rs = acWebClient.getPages();
        if(rs.getIntValue("code")==0){
            throw new RuntimeException(rs.getString("msg"));
        }
        JSONArray categorys = rs.getJSONObject("data").getJSONArray("categorys");

        //删除不存在的application
        List<String> applicationCodes = new ArrayList<>();
        List<String> categoryCodes = new ArrayList<>();
        for(int i=0;i<categorys.size();i++){
            JSONObject json = categorys.getJSONObject(i);
            int updateNum = dictDao.executeUpdate("update ac_category set label=?,parent_code=? where code=? and type=?",json.getString("label"),json.getString("parentCode"),json.getString("code"),json.getString("type"));
            if(updateNum==0){
                dictDao.executeUpdate("insert into ac_category(label,parent_code,code,type) values(?,?,?,?)",json.getString("label"),json.getString("parentCode"),json.getString("code"),json.getString("type"));
            }

            //执行更新或插入操作
            if("category".equals(json.getString("type"))){
                categoryCodes.add(json.getString("code"));
            }else if("application".equals(json.getString("type"))){
                applicationCodes.add(json.getString("code"));
            }
        }

        if(!applicationCodes.isEmpty()){
            dictDao.executeUpdate("delete from ac_category where type='application' and code not in (?)",applicationCodes);
        }

        if(!categoryCodes.isEmpty()){
            dictDao.executeUpdate("delete from ac_category where type='category' and code not in (?)",categoryCodes);
        }

        //同步页面，删除不存在的页面
        //查询所有的id信息
        Map<String,Object> pageIds = dictDao.queryMapVT("select id value,max_version text from ac_page");
        JSONArray pages = rs.getJSONObject("data").getJSONArray("pages");
        for(int i=0;i<pages.size();i++){
            JSONObject page = pages.getJSONObject(i);
            String id = page.getString("categoryCode")+"_"+page.getString("code");

            if(pageIds.containsKey(id)){
                //判定最大版本号是否一致
                int curMaxVersion = pageIds.get(id)==null?0: (int) pageIds.get(id);
                int pcrMaxVersion = page.getIntValue("maxVersion");
                if(curMaxVersion<pcrMaxVersion && pcrMaxVersion>0){
                    //代码同步
                    this.getReleaseVersion(id);
                    //max_version
                    dictDao.executeUpdate("update ac_page set label=? where id=?",page.getString("label"),id);
                }else{
                    //max_version
                    dictDao.executeUpdate("update ac_page set label=? where id=?",page.getString("label"),id);
                }

                pageIds.remove(id);
            }else{
                dictDao.executeUpdate("insert into ac_page(label,id,category_code,code,app_type) values(?,?,?,?,?)",page.getString("label"),id,page.getString("categoryCode"),page.getString("code"),page.getString("appType"));
                this.getReleaseVersion(id);
            }
        }

        if(!pageIds.isEmpty()){
            dictDao.executeUpdate("delete from ac_page_versions where page_id in (?)",pageIds.keySet());
            dictDao.executeUpdate("delete from ac_page where id in (?)",pageIds.keySet());
        }
    }


    public String pageRelease(JSONObject param){
        //授权信息
        AppInfo appInfo = AutoCodeHandle.getAppInfo();
        if(appInfo==null){
            throw new RuntimeException("没有设置授权信息，请登陆(https://autocode.net.cn)下载license.lic授权文件，下载后复制到resources目录下，重启应用！");
        }

        JSONObject acSetting = dictDao.queryJSON("select appid from ac_setting");
        if(acSetting.isEmpty() || !appInfo.getAppid().equals(acSetting.getString("appid")) ){
            dictDao.execute("delete from ac_page_versions");
            dictDao.executeUpdate("update ac_page set max_version=?,version=?",-1,-1);
            if (acSetting.isEmpty()){
                dictDao.executeUpdate("insert into ac_setting(appid) values(?)",appInfo.getAppid());
            }else{
                dictDao.executeUpdate("update ac_setting set appid=?",appInfo.getAppid());
            }
        }

        JSONObject json = dictDao.queryJSON("select * from ac_page where id=?",param.getString("id"));
        if(json.isEmpty()){
            return "success:";
        }
        JSONObject pageJson = new JSONObject();
        pageJson.put("categoryCode",json.getString("categoryCode"));
        pageJson.put("code",json.getString("code"));

        JSONArray versions = dictDao.queryJSONArray("select release_time,release_user,version from ac_page_versions where page_id=? order by release_time desc",param.getString("id"));
        if(versions.isEmpty()){
            pageJson.put("version","-1");
        }else{
            pageJson.put("version",versions.getJSONObject(0).getString("version"));
            pageJson.put("releaseTime",versions.getJSONObject(0).getString("releaseTime"));
            pageJson.put("releaseUser",versions.getJSONObject(0).getString("releaseUser"));
        }


        JSONObject res = acWebClient.pageRelease(pageJson);
        if(res.getIntValue("code")==0){
            return "fail:"+res.getString("msg");
        }else{
            DeveloperInfo developerInfo = AutoCodeHandle.getDeveloperInfo();
            if (developerInfo==null){
                return "fail:license授权文件异常或不存在，请更新授权文件！";
            }
            JSONArray array = res.getJSONArray("data");
            if (array==null||array.isEmpty()){
                return "success:"+res.getString("msg");
            }
            int maxVersion = 0;
            for(int i=0;i<array.size();i++){

                JSONObject releasePage = array.getJSONObject(i);
                releasePage.put("pageId",json.getString("id"));
                releasePage.put("updateTime",new Date());
                releasePage.put("updateUser", developerInfo.getUsername());
                maxVersion = releasePage.getIntValue("version");
                dictDao.createJSON(releasePage,"ac_page_versions");
            }
            //保留50个版本
            if(maxVersion>50){
                dictDao.executeUpdate("delete from ac_page_versions where page_id=? and version<?",param.getString("id"),maxVersion-50);
            }
            if (maxVersion>0){
                dictDao.executeUpdate("update ac_page set max_version=?,version=? where id=?",maxVersion,maxVersion,param.getString("id"));
            }
        }
        return "success:更新成功";
    }

    public void batchRelease(){
        //授权信息
        AppInfo appInfo = AutoCodeHandle.getAppInfo();
        if(appInfo==null){
            throw new RuntimeException("没有设置授权信息，请登陆(https://autocode.net.cn)下载license.lic授权文件，下载后复制到resources目录下，重启应用！");
        }

        JSONObject acSetting = dictDao.queryJSON("select appid from ac_setting");
        if(acSetting.isEmpty() || !appInfo.getAppid().equals(acSetting.getString("appid")) ){
            dictDao.execute("delete from ac_page_versions");
            dictDao.executeUpdate("update ac_page set max_version=?,version=?",-1,-1);
            if (acSetting.isEmpty()){
                dictDao.executeUpdate("insert into ac_setting(appid) values(?)",appInfo.getAppid());
            }else{
                dictDao.executeUpdate("update ac_setting set appid=?",appInfo.getAppid());
            }
        }

        DeveloperInfo developerInfo = AutoCodeHandle.getDeveloperInfo();
        if(developerInfo==null){
            return;
        }

        JSONArray pages = dictDao.queryJSONArray("select * from ac_page");
        for(int i=0;i<pages.size();i++){
            JSONObject page = pages.getJSONObject(i);
            JSONObject pageJson = new JSONObject();
            pageJson.put("categoryCode",page.getString("categoryCode"));
            pageJson.put("code",page.getString("code"));

            JSONArray versions = dictDao.queryJSONArray("select release_time,release_user,version from ac_page_versions where page_id=? order by release_time desc",page.getString("id"));
            if(versions.isEmpty()){
                pageJson.put("version","-1");
            }else{
                pageJson.put("version",versions.getJSONObject(0).getString("version"));
                pageJson.put("releaseTime",versions.getJSONObject(0).getString("releaseTime"));
                pageJson.put("releaseUser",versions.getJSONObject(0).getString("releaseUser"));
            }

            JSONObject res = acWebClient.pageRelease(pageJson);
            if(res.getIntValue("code")==1){

                JSONArray array = res.getJSONArray("data");
                if (array==null||array.isEmpty()){
                    continue;
                }
                int maxVersion = 0;
                for(int j=0;j<array.size();j++){
                    JSONObject releasePage = array.getJSONObject(j);
                    releasePage.put("pageId",page.getString("id"));
                    releasePage.put("updateTime",new Date());
                    releasePage.put("updateUser", developerInfo.getUsername());
                    maxVersion = releasePage.getIntValue("version");
                    dictDao.createJSON(releasePage,"ac_page_versions");
                }
                //保留50个版本
                if(maxVersion>50){
                    dictDao.executeUpdate("delete from ac_page_versions where page_id=? and version<?",page.getString("id"),maxVersion-50);
                }
                if (maxVersion>0){
                    dictDao.executeUpdate("update ac_page set max_version=?,version=? where id=?",maxVersion,maxVersion,page.getString("id"));
                }
            }
        }
    }
}
